package com.zj.common.expand

import android.app.Activity
import android.app.AlertDialog
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.paging.PagingSource
import com.zj.common.bean.BaseBean
import com.zj.common.listener.FullCallback
import com.zj.common.listener.OnRationaleListener
import com.zj.common.listener.ShouldRequest
import com.zj.common.listener.SimpleCallback
import com.zj.common.utils.ActivityManage
import com.zj.common.utils.DebugUtils
import com.zj.common.utils.PermissionUtils
import com.zj.common.utils.SimplePager
import kotlinx.coroutines.launch

fun ViewModel.requestFullCallback(
    vararg permissions: String,
    onGranted: (granted: List<String>) -> Unit,
    onDenied: (shouldRequest: ShouldRequest) -> Unit,
    onCancel: (() -> Unit)? = null
) {
    PermissionUtils.permission(*permissions)
        .rationale(object : OnRationaleListener {
            override fun rationale(activity: Activity, shouldRequest: ShouldRequest) {
                shouldRequest.again(true)
            }
        }).callback(object : FullCallback {
            override fun onGranted(granted: List<String>) {
                onGranted.invoke(granted)
            }

            override fun onDenied(
                deniedForever: List<String>,
                denied: List<String>,
                shouldRequest: ShouldRequest
            ) {
                if (deniedForever.isNotEmpty()) {
                    AlertDialog.Builder(ActivityManage.getTopActivity())
                        .setTitle(android.R.string.dialog_alert_title)
                        .setMessage("我们需要一些您拒绝的权限或系统无法应用的失败，请手动设置到页面授权，否则该函数不能正常使用！")
                        .setPositiveButton(android.R.string.ok) { _, _ ->
                            PermissionUtils.launchAppDetailsSettings()
                        }
                        .setNegativeButton(android.R.string.cancel) { _, _ ->
                            onCancel?.invoke()
                        }
                        .setCancelable(false)
                        .create()
                        .show()
                    return
                }
                onDenied.invoke(shouldRequest)
            }
        }).request()
}

fun ViewModel.requestSimpleCallback(
    vararg permissions: String,
    onGranted: () -> Unit,
    onDenied: () -> Unit
) {
    PermissionUtils.permission(*permissions)
        .rationale(object : OnRationaleListener {
            override fun rationale(activity: Activity, shouldRequest: ShouldRequest) {
                shouldRequest.again(true)
            }
        }).callback(object : SimpleCallback {
            override fun onGranted() {
                onGranted.invoke()
            }

            override fun onDenied() {
                onDenied.invoke()
            }
        }).request()
}
